﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using SageKing.OpenIddict.UI.Identity.Core;

namespace SageKing.OpenIddict.UI.Identity.Api;

public class AccountApiHttpClient<TIdentityUser, TKey> : AccountApiService<TIdentityUser, TKey>, IAccountApiClient
      where TKey : IEquatable<TKey>
      where TIdentityUser : IdentityUser<TKey>, new()
{
    private readonly IAccountService _accountService;
    private readonly HttpClient _httpClient;

    public AccountApiHttpClient(
      IAccountService accountService,
      IHttpClientFactory httpClientFactory
    ) : base(accountService)
    {
        _accountService = accountService
          ?? throw new ArgumentNullException(nameof(accountService));

        // 在创建 HttpClient 实例之前设置
        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;

        _httpClient = httpClientFactory.CreateClient(HttpClientConsts.HttpClientIssuerKey) ?? throw new ArgumentNullException(nameof(httpClientFactory));
        _httpClient.CheckBaseAddress();
    }

    public async Task<SignInResultVM> PasswordSignInAsync(LoginViewModel model)
    {
        var url = "api/accounts/passwordsignin";
        var rsp = await _httpClient.PostAsJsonAsync(url, model);
        //rsp.EnsureSuccessStatusCode();
        var result = await rsp.Content.FromJSONAsync<SignInResultVM>();
        return result;
    }
}
